package com.hspedu.newData.dmsxl.图;
/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-28 
 * @Version: 1.0
 */

public class LC200岛屿数量 {

    // 深搜版
    private int[][] dir = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};

    public int numIslands(char[][] grid) {

        int x = grid.length;
        int y = grid[0].length;

        boolean[][] visited = new boolean[x][y];

        int res = 0;
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                if (!visited[i][j] && grid[i][j] == '1'){
                    res++;
                    visited[i][j] = true;
                    dfs(grid, visited,i,j);
                }
            }
        }
        return res;
    }

    public void dfs(char[][] grid, boolean[][] visited, int x, int y){

        for (int i = 0; i < 4; i++) {
            int nextX = x + dir[i][0];
            int nextY = y + dir[i][1];

            if (nextX<0||nextY<0||nextX>= grid.length||nextY>=grid[0].length){
                continue;
            }

            if (!visited[nextX][nextY] && grid[nextX][nextY]=='1'){
                visited[nextX][nextY] = true;
                dfs(grid, visited,nextX,nextY);
            }
        }
    }

}
